package com.hongxun.design.utils;


import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;

import com.hongxun.design.MyApp;
import com.hongxun.design.R;
import com.hongxun.design.constant.Constant;
import com.hongxun.design.fragments.BaseFragment;
import com.hongxun.design.fragments.EncyclopediasFragment;
import com.hongxun.design.fragments.HomeFragmentNew;
import com.hongxun.design.fragments.MyFragment;
import com.hongxun.design.fragments.ProjectFragment;
import com.hongxun.design.mytools.MyLog;
import com.hongxun.design.ui.headandbottonpanel.BottomControlPanel;


/**
 * Created by zerdoor_pc on 2016/4/26.
 */
public class FragmentUtil {
    private FragmentManager fragmentManager = null;
    private FragmentTransaction fragmentTransaction = null;
    public static String currFragTag = "";
    public static Fragment currFragment = null;//记录上次的fragment防止activity返回时异常
    public static FragmentUtil intence;
    private FragmentActivity activity;

    public void finish() {
//        fragmentManager = null;
//        fragmentTransaction = null;
//        currFragment = null;
    }

    FragmentUtil(FragmentActivity activity) {
        fragmentManager = activity.getSupportFragmentManager();
        this.activity = activity;
    }

    public static FragmentUtil getIntence(FragmentActivity activity) {
        if (intence == null) {
            intence = new FragmentUtil(activity);
        }
        return intence;
    }


    public void setDefaultFirstFragment(String tag, BottomControlPanel bottomPanel) {
        MyLog.L(MyApp.AppName + "setDefaultFirstFragment enter... currFragTag = " + currFragTag);
        setTabSelection(tag);
        bottomPanel.defaultBtnChecked();
        MyLog.L(MyApp.AppName + "setDefaultFirstFragment exit...");
    }

    private void commitTransactions(String tag, BaseFragment f) {
        if (f == null) return;
        if (fragmentTransaction != null && !fragmentTransaction.isEmpty()) {
            fragmentTransaction.commitAllowingStateLoss();
            currFragTag = tag;
            currFragment = f;
            f.Refresh();
//            fragmentTransaction = null;
        }
    }

    private FragmentTransaction ensureTransaction() {
        if (fragmentTransaction == null) {
            fragmentTransaction = fragmentManager.beginTransaction();
            fragmentTransaction
                    .setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);

        }
        return fragmentTransaction;

    }

    private void attachFragment2(int layout, Fragment f, String tag) {
        if (f != null) {
            if (f.isDetached()) {
                ensureTransaction();
                fragmentTransaction.attach(f);

            } else if (!f.isAdded()) {
                ensureTransaction();
                fragmentTransaction.add(layout, f, tag);

            }
        }
    }

    private BaseFragment attachFragment(int layout, BaseFragment f, String tag) {
        if (f != null) {

            if (f.isDetached()) {
                ensureTransaction();
                fragmentTransaction.attach(f);
            } else if (!f.isAdded()) {
                ensureTransaction();
                fragmentTransaction.add(layout, f, tag);

            } else {
                fragmentTransaction.show(f); // 隐藏当前的fragment，显示下一个
            }
        }
        return f;
    }

    private BaseFragment getFragment(String tag) {

        BaseFragment f = (BaseFragment) fragmentManager.findFragmentByTag(tag);

        if (f == null) {
            MyLog.L(MyApp.AppName + "fragment = null tag = " + tag);
            f = BaseFragment.newInstance(activity, tag);
        }
        return f;

    }

    //隐藏fragment
    private void hideFragment(Fragment f) {
        MyLog.L(MyApp.AppName + "fragment =" + f + "  currFragment=" + currFragment);
        MyLog.L(MyApp.AppName + "fragment isDetached=" + f.isDetached());
        if (f != null && !f.isDetached()) {
            ensureTransaction();
            //fragmentTransaction.detach(f);
            fragmentTransaction.hide(f);
        }
//        if (currFragment != null && currFragment != f) {
//            ensureTransaction();
//            MyLog.L(MyApp.AppName + "fragment detach： " + currFragment);
//            fragmentTransaction.detach(currFragment);
//            currFragment = null;
//        }

    }

    //结束
    private void detachFragment(Fragment f) {

        if (f != null && !f.isDetached()) {
            ensureTransaction();
            fragmentTransaction.detach(f);
        }
    }


    /**
     * 切换fragment
     *
     * @param tag
     */
    private void switchFragment(String tag) {
        if (TextUtils.equals(tag, currFragTag)) {
            return;
        }
        //把上一个fragment detach掉

        if (currFragTag != null && !currFragTag.equals("")) {
//            detachFragment(getFragment(currFragTag));
            hideFragment(getFragment(currFragTag));
        } else {
            if (currFragment != null) {
                ensureTransaction();
                MyLog.L(MyApp.AppName + "fragment detach： " + currFragment);
                fragmentTransaction.detach(currFragment);
                currFragment = null;
            }
        }

        commitTransactions(tag, attachFragment(R.id.fragment_content, getFragment(tag), tag));
    }

    /**
     * 设置选中的Tag
     *
     * @param tag
     */
    public void setTabSelection(String tag) {
        switchF(tag);
//        // 开启一个Fragment事务
//        if (fragmentManager == null) {
//            fragmentManager = activity.getSupportFragmentManager();
//        }
//        fragmentTransaction = fragmentManager.beginTransaction();
//        switchFragment(tag);
    }

    FragmentManager FM;
    BaseFragment currf;
    public String currtag = "";
    public ProjectFragment projectFragment = new ProjectFragment();//项目Fragment
    //    public HomeFragment homeFragment = new HomeFragment();//首页Fragment
    public HomeFragmentNew homeFragment = new HomeFragmentNew();//首页Fragment
    public EncyclopediasFragment encyclopediasFragment = new EncyclopediasFragment();//百科Fragment
    public MyFragment myFragment = new MyFragment();//我的Fragment

    public void destory() {
        projectFragment = null;
        homeFragment = null;
        encyclopediasFragment = null;
        myFragment = null;
    }

    private void switchF(String tag) {
        if (FM == null) {
            FM = activity.getSupportFragmentManager();
        }

        if (currtag.equals(tag)) return;

        switch (tag) {
            case Constant.FRAGMENT_FLAG_PROJECT:
                replaceFragment(projectFragment, tag);
                break;
            case Constant.FRAGMENT_FLAG_HOME:
                replaceFragment(homeFragment, tag);
                break;
            case Constant.FRAGMENT_FLAG_ENCYCLOPEDIAS:
                replaceFragment(encyclopediasFragment, tag);
                break;
            case Constant.FRAGMENT_FLAG_MY:
                replaceFragment(myFragment, tag);
                break;

        }
    }

    private void replaceFragment(BaseFragment newFragment, String tag) {
        try {
            if (currf == newFragment) return;
            FragmentTransaction transaction = FM.beginTransaction();
            if (!newFragment.isAdded()) {
                transaction.add(R.id.fragment_content, newFragment, tag);
            } else {
                transaction.show(newFragment);
            }
            if (currf != null && currf != newFragment) {
                transaction.hide(currf);
            }
            transaction.commit();
            currf = newFragment;
            currtag = tag;
            newFragment.Refresh();
        } catch (Exception e) {
        }

    }


}
